package com.hooya.fa.eu.biz.dao.manager.special;

import com.hooya.fa.eu.api.bo.stk.ReturnedRecordBO;
import com.hooya.fa.eu.biz.dao.entity.PlaceMatchDict;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 退货Manager
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/3/7
 * @Version 1.0.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class ReturnedGoodsManager {

    /**
     * 筛选符合条件的退货数据
     *
     * @param returnedList      退货数据
     * @param placeMatchDictMap place匹配字典
     * @param storeMap          店铺字典
     * @return 退货结果集
     */
    public List<ReturnedRecordBO> getEligibleReturnGoodsData(List<ReturnedRecordBO> returnedList,
                                                             Map<String, PlaceMatchDict> placeMatchDictMap,
                                                             Map<String, String> storeMap) {
        returnedList = returnedList.stream()
                .filter(l -> StringUtils.isNotBlank(l.getDianPu())).collect(Collectors.toList());
        for (ReturnedRecordBO bo : returnedList) {
            PlaceMatchDict place = placeMatchDictMap.get(bo.getPlace());
            if (Objects.nonNull(place)) {
                if ("restock".equals(place.getType())) {
                    bo.setPlace(place.getRealWhId());
                }
            }
            PlaceMatchDict chck = placeMatchDictMap.get(bo.getChck());
            if (Objects.nonNull(chck)) {
                if ("restock".equals(chck.getType())) {
                    bo.setChck(chck.getRealWhId());
                }
            }
            if (StringUtils.isNotBlank(storeMap.get(bo.getDianPu()))) {
                bo.setCompany(storeMap.get(bo.getDianPu()));
            }
        }
        return new ArrayList<>(returnedList.stream()
                .collect(Collectors.groupingBy(l -> l.getOrderDate() + l.getSku() + l.getPlace()
                                + l.getCompany() + l.getChck(),
                        Collectors.collectingAndThen(
                                Collectors.reducing((d1, d2) -> ReturnedRecordBO.builder()
                                        .orderDate(d1.getOrderDate()).sku(d1.getSku()).place(d1.getPlace())
                                        .company(d1.getCompany()).chck(d1.getChck())
                                        .sl(d1.getSl() + d2.getSl()).build()),
                                Optional::get
                        )))
                .values());
    }
}
